package SSIHaSTCChannel;
use strict;
use DataCollectionChannel;
use vars qw /@ISA/;
@ISA = ("DataCollectionChannel");

sub new{
	my $class = shift; 
	my $self = {};
	$self->{URL} = 'http://ssi.com.vn/HaSTC/StandardData/HaSTC/SSI_HN_PRICE_ONLINE_TABLE.XML';
	$self->{STOCK_FIELD_FORMAT} = [ 'MCK', 'CEILING', 'FLOORPRICE', 'GTC', 'FRoom', 'FKLM', 'FKLB', 'GTN', 'GCN', 'GBQGQ', 'TKLK', 'GDK', 'KLKDK', 'CHANGEPRICE', 'GM3', 'KLM3', 'GM2', 'KLM2', 'GM1', 'KLM1', 'GB1', 'KLB2', 'GB2', 'KLB3', 'GB3'];
	$self->{MARKET_FIELD_FORMAT} = [ 'VNIndex', 'ChangeIndex', 'TotalVol', 'TotalValue', 'Clock', 'Notes', 'InSession'];
	$self->{SECURITY_CENTER_CODE} = 'HaSTC';
	bless $self, $class;
	return $self; 
}
###################################
## create Mechanize browser		##
###################################
sub create_browser{
	 my $self = shift;	  
	 $self->{BROWSER} = WWW::Mechanize->new(
	  	agent => 'Mozilla/5.0 (compatible; MSIE 4.01; Windows95)'	  	
	 ) unless $self->{BROWSER};	 
}

##################################
##	get html page of given url	##
##################################
sub get_data_source{
	my $self = shift;
	$self->create_browser;
	my $browser = $self->{BROWSER};
	$browser->parse_head(0);	  
 	my $resp = $browser->get($self->{URL});
 	return ($resp->content, $resp->is_success, $resp->status_line);   	
}

sub get_stock_info_set{
	my $self = shift;
	my $cur_time = time();
	my $content;
	my $is_success;
	my $status_line;
	while(time < $cur_time + $self->{TIMEOUT}){
		$self->{STATUS}->{CODE} = 'CONNECTING';
		($content, $is_success, $status_line) = $self->get_data_source();	
		if (!$is_success){
			$self->{STATUS}->{CODE} = 'RECONNECT';
			$self->{STATUS}->{MSG} = "Can't fetch data source | Channel $self->{NAME}: $status_line";
			next;	
		}else{
			$self->{STATUS}->{CODE} = 'OK';
			$self->{STATUS}->{MSG} = "Data source is fetched| Channel $self->{NAME}: $status_line";
			last;			
		}
	}
	if ($self->{STATUS}->{CODE} ne 'OK'){
		$self->{STATUS}->{CODE} = 'TIMEOUT';
		$self->{STATUS}->{MSG} = 'Can\'t fetch data source| Channel $self->{NAME}: connection timeout';
		return (undef,$self->{STATUS}->{CODE});		
	}
	return ($content, $self->{STATUS}->{CODE});	
}

1;